package com.atguigu.juc02;


import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Resource {
    //    public synchronized void m1() {
//        System.out.println("come in ..." + Thread.currentThread().getName());
//        try {
//            TimeUnit.SECONDS.sleep(3);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//    }
    private Lock lock = new ReentrantLock();

    public void m1() throws InterruptedException {

        if (lock.tryLock(5, TimeUnit.SECONDS)) {
            try {
                System.out.println("come in ..." + Thread.currentThread().getName());
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        } else {
            System.out.println("抢锁失败");
        }

    }

}


public class SyncVsReentrantLockDemo2 {
    public static void main(String[] args) {
        Resource resource = new Resource();

        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                try {
                    resource.m1();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }, i + 1 + "").start();
        }

    }
}
